import NodeRSA from 'node-rsa';

const publicKey = `-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA00oiWLD+y0MWyyX+gKFj
P/vuzPwaUJyUk/pJp7c42U51P0md+LCFheK19J0ED10vZxZCAmeCB49ZiFexbvm0
O33rheBpxKc1HJ7o131qpIqHOZfdqqoI/WY1e2EZ4aVPKN8cWBoYIbq3YwT2t3ry
JnA6ttGQjifRAQR1pJC3MgF2PBh8vFE8EzsBMsb1KJY5v5DGBGYbipWaSdJsL+yO
GpxYk7X5tZFibXsdAm6nL2vVDOdl1ex18Q8KY4ol8ZsP5FRKpOMpFBv5KgTfLAm4
qvmnvKAIS9vsXU3r4sXCMXsQL9y/5RlF0+GHDuIEd07fc9DI1eZVE48xjC7FxsPh
9QIDAQAB
-----END PUBLIC KEY-----
`;

const privateKey = `-----BEGIN PRIVATE KEY-----
MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDTSiJYsP7LQxbL
Jf6AoWM/++7M/BpQnJST+kmntzjZTnU/SZ34sIWF4rX0nQQPXS9nFkICZ4IHj1mI
V7Fu+bQ7feuF4GnEpzUcnujXfWqkioc5l92qqgj9ZjV7YRnhpU8o3xxYGhghurdj
BPa3evImcDq20ZCOJ9EBBHWkkLcyAXY8GHy8UTwTOwEyxvUoljm/kMYEZhuKlZpJ
0mwv7I4anFiTtfm1kWJtex0Cbqcva9UM52XV7HXxDwpjiiXxmw/kVEqk4ykUG/kq
BN8sCbiq+ae8oAhL2+xdTevixcIxexAv3L/lGUXT4YcO4gR3Tt9z0MjV5lUTjzGM
LsXGw+H1AgMBAAECggEAHhvTVyYpuNdfmSVZ5gSZexWwit9l9JTLi2bANjkizbyj
cphP/Y9SB6kt2qTBXlseFSeT0nnjiqY/0PEGJNVKfKvN8y7ug4p8RA7VCVgi6T2g
VXGxsc83Jrz45BMLOB9xb1aT2G4ngC72URL1AWJwvU+C3mhwnAFKhEWZ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`;

const publicNodeRsa = new NodeRSA(publicKey, undefined, {
  encryptionScheme: 'pkcs1',
});
const privateNodeRsa = new NodeRSA(privateKey, undefined, {
  encryptionScheme: 'pkcs1',
});

/**
 * 公钥加密
 * @param plaintext 待加密的明文数据
 * @returns
 */
export function encrypt(plaintext: any) {
  return publicNodeRsa.encrypt(
    typeof plaintext === 'string' ? test : JSON.stringify(plaintext),
    'base64',
  );
}

/**
 * 私钥解密
 * @param ciphertext 待解密的密文字符
 * @returns
 */
export function decrypt(ciphertext: string) {
  try {
    if (typeof ciphertext !== 'string') return ciphertext;
    const decryptData = privateNodeRsa.decrypt(ciphertext, 'utf8');
    return JSON.parse(decryptData);
  } catch (error) {
    throw error;
  }
}

/**
 * 获取参数加密公钥
 * @returns
 */
export function getPublicKey() {
  return publicKey;
}
